package cn.hsw.platform.core.configure;

import cn.hsw.platform.core.util.StrUtil;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValue;
import org.springframework.web.bind.ServletRequestDataBinder;

import javax.servlet.ServletRequest;
import java.util.LinkedList;
import java.util.List;

/**
 * 将所有的下划线参数转换成驼峰
 * @author 李子木
 * @date 2020-11-02
 */
public class CustomServletRequestDataBinder extends ServletRequestDataBinder {

    public CustomServletRequestDataBinder(final Object target) {
        super(target);
    }

    /** 遍历请求参数对象 把请求参数的名转换成驼峰体
     * 重写addBindValues绑定数值的方法
     * @param mutablePropertyValues 请求参数列表
     * @param servletRequest 请求
     */
    @Override
    protected void addBindValues(MutablePropertyValues mutablePropertyValues, ServletRequest servletRequest) {
        List<PropertyValue> pvs = mutablePropertyValues.getPropertyValueList();
        List<PropertyValue> adds = new LinkedList<>();
        for (PropertyValue pv : pvs) {
            String name = pv.getName();
            String camel = StrUtil.underLineToCamel(name);
            if (!name.equals(camel)) {
                adds.add(new PropertyValue(camel, pv.getValue()));
            }else{
                adds.add(pv);
            }
        }
        pvs.clear();
        pvs.addAll(adds);
    }

}
